﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GDI_应用案例.Pages.Controls
{
    public class ShadeLabel : Label
    {
        private LinearGradientMode _linearGradientMode = LinearGradientMode.Horizontal;
        private Color _upColor = Color.Red;
        private Color _downColor = Color.Blue;
        private RectangleF _textRect = RectangleF.Empty;
        public LinearGradientMode GradientMode
        {
            get => _linearGradientMode;
            set
            {
                _linearGradientMode = value;
                _textRect = RectangleF.Empty;
                this.Invalidate();
            }
        }
        public Color UpColor
        {
            get => _upColor;
            set
            {
                _upColor = value;
                _textRect = RectangleF.Empty;
                this.Invalidate();
            }
        }
        public Color DownColor
        {
            get => _downColor;
            set
            {
                _downColor = value;
                _textRect = RectangleF.Empty;
                this.Invalidate();
            }
        }
        public override string Text
        {
            get => base.Text;
            set
            {
                _textRect = RectangleF.Empty;
                base.Text = value;
            }
        }
        public override Font Font
        {
            get => base.Font;
            set
            {
                _textRect = RectangleF.Empty;
                base.Font = value;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.Clear(this.BackColor);

            if (_textRect.IsEmpty)
                _textRect = CreateRectangleF(this.Text, this.Font, this.ClientSize, this.Padding, g);

            using (LinearGradientBrush brush = new LinearGradientBrush(_textRect, UpColor, DownColor, GradientMode))
            {
                // 绘制文字
                g.DrawString(this.Text, this.Font, brush, _textRect.X, _textRect.Y);
            }
        }

        protected RectangleF CreateRectangleF(string text, Font font, Size clientSize, Padding padding, Graphics g)
        {
            SizeF textSize = g.MeasureString(text, font);
            // 计算文字绘制的位置，考虑Padding
            float x = (clientSize.Width - textSize.Width) / 2 + padding.Left - padding.Right;
            float y = (clientSize.Height - textSize.Height) / 2 + padding.Top - padding.Bottom;
            return new RectangleF(x, y, textSize.Width, textSize.Height);
        }
    }
}
